package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.SiteContentManager;
import com.xyzh05.model.SiteContent;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class SiteContentAction extends BaseAction implements Preparable {
    private SiteContentManager siteContentManager;
    private List siteContents;
    private SiteContent siteContent;
    private Long id;
    private String query;

    public void setSiteContentManager(SiteContentManager siteContentManager) {
        this.siteContentManager = siteContentManager;
    }

    public List getSiteContents() {
        return siteContents;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String siteContentId = getRequest().getParameter("siteContent.id");
            if (siteContentId != null && !siteContentId.equals("")) {
                siteContent = siteContentManager.get(new Long(siteContentId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        siteContents = siteContentManager.search(query, SiteContent.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public SiteContent getSiteContent() {
        return siteContent;
    }

    public void setSiteContent(SiteContent siteContent) {
        this.siteContent = siteContent;
    }

    public String delete() {
        siteContentManager.remove(siteContent.getId());
        saveMessage(getText("siteContent.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            siteContent = siteContentManager.get(id);
        } else {
            siteContent = new SiteContent();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (siteContent.getId() == null);

        siteContentManager.save(siteContent);

        String key = (isNew) ? "siteContent.added" : "siteContent.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}